package com.zhhl.redis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;

public abstract class RedisGeneratorDao<K extends Serializable, V extends Serializable>
{

  @Resource
  protected RedisTemplate<K, V> redisTemplate;

  public void setRedisTemplate(RedisTemplate<K, V> redisTemplate)
  {
    this.redisTemplate = redisTemplate;
  }

  protected byte[] serialize(Object object)
  {
    ObjectOutputStream oos = null;
    ByteArrayOutputStream baos = null;
    try {
      baos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(baos);
      oos.writeObject(object);
      return baos.toByteArray();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  protected Object unserialize(byte[] bytes)
  {
    ByteArrayInputStream bais = null;
    try {
      bais = new ByteArrayInputStream(bytes);
      ObjectInputStream ois = new ObjectInputStream(bais);
      return ois.readObject();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}